package com.weijian.controller;

import com.weijian.common.Result;
import com.weijian.dto.ChunkUploadRequest;
import com.weijian.dto.CompleteUploadRequest;
import com.weijian.dto.InitUploadRequest;
import com.weijian.entity.VideoInfo;
import com.weijian.service.ChunkUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分片上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
@Tag(name = "分片上传管理", description = "提供大文件分片上传相关接口")
public class ChunkUploadController {

    private final ChunkUploadService chunkUploadService;

    /**
     * 初始化上传任务
     */
    @PostMapping("/init")
    @Operation(summary = "初始化上传任务", description = "创建一个新的分片上传任务，返回任务ID")
    public Result<?> initUpload(@RequestBody InitUploadRequest request) {
        try {
            log.info("初始化上传任务: {}", request.getFileName());
            
            if (request.getFileName() == null || request.getFileName().trim().isEmpty()) {
                return Result.error("文件名不能为空");
            }
            
            if (request.getFileSize() == null || request.getFileSize() <= 0) {
                return Result.error("文件大小必须大于0");
            }
            
            if (request.getTotalChunks() == null || request.getTotalChunks() <= 0) {
                return Result.error("分片数必须大于0");
            }
            
            Object response = chunkUploadService.initUpload(request);
            return Result.success("初始化成功", response);
            
        } catch (Exception e) {
            log.error("初始化上传失败: {}", e.getMessage(), e);
            return Result.error("初始化上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传分片
     */
    @PostMapping("/chunk")
    @Operation(summary = "上传分片", description = "上传单个分片文件")
    public Result<?> uploadChunk(ChunkUploadRequest request) {
        try {
            log.info("上传分片: taskId={}, chunk={}", request.getTaskId(), request.getChunkNumber());
            
            if (request.getTaskId() == null || request.getTaskId().trim().isEmpty()) {
                return Result.error("任务ID不能为空");
            }
            
            if (request.getChunkNumber() == null || request.getChunkNumber() < 0) {
                return Result.error("分片序号不能为空");
            }
            
            if (request.getChunk() == null || request.getChunk().isEmpty()) {
                return Result.error("分片文件不能为空");
            }
            
            Object response = chunkUploadService.uploadChunk(request);
            return Result.success("分片上传成功", response);
            
        } catch (Exception e) {
            log.error("分片上传失败: {}", e.getMessage(), e);
            return Result.error("分片上传失败: " + e.getMessage());
        }
    }

    /**
     * 完成上传
     */
    @PostMapping("/complete")
    @Operation(summary = "完成上传", description = "合并所有分片完成文件上传")
    public Result<?> completeUpload(@RequestBody CompleteUploadRequest request) {
        try {
            log.info("完成上传: {}", request.getTaskId());
            
            if (request.getTaskId() == null || request.getTaskId().trim().isEmpty()) {
                return Result.error("任务ID不能为空");
            }
            
            VideoInfo videoInfo = chunkUploadService.completeUpload(request);
            return Result.success("上传完成", videoInfo);
            
        } catch (Exception e) {
            log.error("完成上传失败: {}", e.getMessage(), e);
            return Result.error("完成上传失败: " + e.getMessage());
        }
    }

    /**
     * 获取已上传的分片列表
     */
    @GetMapping("/chunks/{taskId}")
    @Operation(summary = "获取已上传分片列表", description = "查询指定任务已上传的分片序号列表")
    public Result<?> getUploadedChunks(
            @Parameter(description = "任务ID", example = "uuid-task-123", required = true)
            @PathVariable String taskId) {
        try {
            log.info("获取已上传分片列表: {}", taskId);
            
            if (taskId == null || taskId.trim().isEmpty()) {
                return Result.error("任务ID不能为空");
            }
            
            List<Integer> chunks = chunkUploadService.getUploadedChunks(taskId);
            return Result.success("获取成功", chunks);
            
        } catch (Exception e) {
            log.error("获取分片列表失败: {}", e.getMessage(), e);
            return Result.error("获取分片列表失败: " + e.getMessage());
        }
    }
}